<template>
    <view class="container">
        <!-- 统计卡片 -->
        <view class="stat-cards">
            <view class="stat-card">
                <text class="label">今日订单</text>
                <text class="value">{{ statistics.todayCount }}</text>
            </view>
            <view class="stat-card">
                <text class="label">今日收入</text>
                <text class="value">¥{{ statistics.todayIncome }}</text>
            </view>
        </view>

        <!-- 搜索栏 -->
        <view class="search-bar">
            <view class="search-input">
                <image src="/static/images/admin/search.png"></image>
                <input 
                    type="text"
                    v-model="searchKey"
                    placeholder="搜索订单号/用户"
                    @confirm="handleSearch"
                />
            </view>
            <view class="filter-btn" @tap="showFilter">
                <image src="/static/images/admin/filter.png"></image>
            </view>
        </view>

        <!-- 状态标签 -->
        <scroll-view class="status-tags" scroll-x>
            <view 
                class="tag"
                :class="{ active: currentStatus === status.value }"
                v-for="status in statusOptions"
                :key="status.value"
                @tap="filterByStatus(status.value)"
            >
                {{ status.label }}
            </view>
        </scroll-view>

        <!-- 订单列表 -->
        <scroll-view 
            class="order-list"
            scroll-y
            @scrolltolower="loadMore"
            :refresher-enabled="true"
            :refresher-triggered="refreshing"
            @refresherrefresh="refresh"
        >
            <view 
                class="order-item"
                v-for="item in orderList"
                :key="item.id"
                @tap="goToDetail(item)"
            >
                <view class="order-header">
                    <view class="order-no">订单号：{{ item.orderNo }}</view>
                    <view class="order-status" :class="item.status">
                        {{ getStatusText(item.status) }}
                    </view>
                </view>
                
                <view class="device-info">
                    <text class="device-no">设备编号：{{ item.deviceNo }}</text>
                    <view class="location">
                        <image src="/static/images/admin/location.png"></image>
                        <text>{{ item.hospitalName }} {{ item.departmentName }}</text>
                    </view>
                </view>

                <view class="user-info">
                    <image class="avatar" :src="item.userAvatar" mode="aspectFill"></image>
                    <text class="nickname">{{ item.userNickname }}</text>
                    <text class="phone">{{ item.userPhone }}</text>
                </view>

                <view class="order-info">
                    <view class="info-item">
                        <text class="label">开始时间</text>
                        <text class="value">{{ item.startTime }}</text>
                    </view>
                    <view class="info-item">
                        <text class="label">使用时长</text>
                        <text class="value">{{ formatDuration(item.duration) }}</text>
                    </view>
                    <view class="info-item">
                        <text class="label">订单金额</text>
                        <text class="value price">¥{{ item.amount }}</text>
                    </view>
                </view>

                <view class="actions" v-if="item.status === 'using'">
                    <button 
                        class="action-btn warn"
                        @tap.stop="handleForceEnd(item)"
                    >
                        强制结束
                    </button>
                </view>
            </view>

            <!-- 加载更多 -->
            <view class="loading" v-if="loading">加载中...</view>
            <view class="no-more" v-if="noMore">没有更多了</view>
        </scroll-view>

        <!-- 筛选弹窗 -->
        <uni-popup ref="filterPopup" type="right">
            <view class="filter-popup">
                <!-- 筛选内容与设备列表类似，这里省略 -->
            </view>
        </uni-popup>

        <!-- 强制结束确认弹窗 -->
        <uni-popup ref="endConfirmPopup" type="dialog">
            <uni-popup-dialog
                type="warn"
                title="确认强制结束"
                content="是否确认强制结束该订单？用户将按照实际使用时长扣费。"
                :before-close="true"
                @confirm="confirmForceEnd"
                @close="cancelForceEnd"
            />
        </uni-popup>
    </view>
</template>

<script>
import { getOrderList, getOrderStatistics, forceEndOrder } from '@/api/order'
import store from '@/utils/store'

export default {
    data() {
        return {
            statistics: {
                todayCount: 0,
                todayIncome: '0.00'
            },
            searchKey: '',
            currentStatus: 'all',
            statusOptions: [
                { label: '全部', value: 'all' },
                { label: '使用中', value: 'using' },
                { label: '已完成', value: 'completed' },
                { label: '已取消', value: 'cancelled' },
                { label: '已退款', value: 'refunded' }
            ],
            orderList: [],
            page: 1,
            pageSize: 10,
            loading: false,
            refreshing: false,
            noMore: false,
            selectedOrder: null
        }
    },
    onLoad() {
        if (!store.isAdmin()) {
            uni.showToast({
                title: '无权限访问',
                icon: 'none'
            })
            setTimeout(() => {
                uni.switchTab({
                    url: '/pages/index/index'
                })
            }, 1500)
            return
        }
        
        this.loadStatistics()
        this.loadOrderList()
    },
    methods: {
        // 加载统计数据
        async loadStatistics() {
            try {
                const res = await getOrderStatistics()
                this.statistics = res
            } catch (error) {
                console.error('获取统计数据失败', error)
            }
        },
        
        // 加载订单列表
        async loadOrderList(reset = false) {
            if (this.loading) return
            
            if (reset) {
                this.page = 1
                this.orderList = []
                this.noMore = false
            }
            
            try {
                this.loading = true
                const res = await getOrderList({
                    page: this.page,
                    pageSize: this.pageSize,
                    status: this.currentStatus === 'all' ? '' : this.currentStatus,
                    keyword: this.searchKey
                })
                
                this.orderList = [...this.orderList, ...res.list]
                this.noMore = res.list.length < this.pageSize
                this.page++
            } catch (error) {
                console.error('获取订单列表失败', error)
            } finally {
                this.loading = false
                this.refreshing = false
            }
        },
        
        // 搜索
        handleSearch() {
            this.loadOrderList(true)
        },
        
        // 状态筛选
        filterByStatus(status) {
            this.currentStatus = status
            this.loadOrderList(true)
        },
        
        // 下拉刷新
        refresh() {
            this.refreshing = true
            this.loadOrderList(true)
        },
        
        // 上拉加载更多
        loadMore() {
            if (!this.noMore) {
                this.loadOrderList()
            }
        },
        
        // 格式化时长
        formatDuration(minutes) {
            const hours = Math.floor(minutes / 60)
            const mins = minutes % 60
            return `${hours}小时${mins}分钟`
        },
        
        // 获取状态文本
        getStatusText(status) {
            const statusMap = {
                'using': '使用中',
                'completed': '已完成',
                'cancelled': '已取消',
                'refunded': '已退款'
            }
            return statusMap[status] || status
        },
        
        // 跳转详情
        goToDetail(item) {
            uni.navigateTo({
                url: `/pages/admin/order/detail?id=${item.id}`
            })
        },
        
        // 强制结束
        handleForceEnd(item) {
            this.selectedOrder = item
            this.$refs.endConfirmPopup.open()
        },
        
        // 确认强制结束
        async confirmForceEnd() {
            try {
                await forceEndOrder(this.selectedOrder.id)
                uni.showToast({
                    title: '操作成功',
                    icon: 'success'
                })
                this.loadOrderList(true)
            } catch (error) {
                uni.showToast({
                    title: '操作失败',
                    icon: 'none'
                })
            } finally {
                this.$refs.endConfirmPopup.close()
                this.selectedOrder = null
            }
        },
        
        // 取消强制结束
        cancelForceEnd() {
            this.$refs.endConfirmPopup.close()
            this.selectedOrder = null
        }
    }
}
</script>

<style lang="scss" scoped>
.container {
    min-height: 100vh;
    background-color: #f5f5f5;
    padding: 20rpx;
    
    .stat-cards {
        display: flex;
        gap: 20rpx;
        margin-bottom: 20rpx;
        
        .stat-card {
            flex: 1;
            background: #fff;
            border-radius: 12rpx;
            padding: 20rpx;
            
            .label {
                font-size: 24rpx;
                color: #666;
            }
            
            .value {
                display: block;
                font-size: 36rpx;
                color: #333;
                font-weight: bold;
                margin-top: 10rpx;
            }
        }
    }
    
    // 搜索栏样式与设备列表类似，这里省略
    
    .order-list {
        .order-item {
            background: #fff;
            border-radius: 12rpx;
            padding: 30rpx;
            margin-bottom: 20rpx;
            
            .order-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 20rpx;
                
                .order-no {
                    font-size: 28rpx;
                    color: #666;
                }
                
                .order-status {
                    padding: 4rpx 16rpx;
                    border-radius: 20rpx;
                    font-size: 24rpx;
                    
                    &.using {
                        background: #e3f2fd;
                        color: #2196f3;
                    }
                    
                    &.completed {
                        background: #e8f5e9;
                        color: #4caf50;
                    }
                    
                    &.cancelled {
                        background: #f5f5f5;
                        color: #9e9e9e;
                    }
                    
                    &.refunded {
                        background: #fff3e0;
                        color: #ff9800;
                    }
                }
            }
            
            .device-info {
                margin-bottom: 20rpx;
                
                .device-no {
                    font-size: 28rpx;
                    color: #333;
                    margin-bottom: 10rpx;
                    display: block;
                }
                
                .location {
                    display: flex;
                    align-items: center;
                    
                    image {
                        width: 32rpx;
                        height: 32rpx;
                        margin-right: 10rpx;
                    }
                    
                    text {
                        font-size: 28rpx;
                        color: #666;
                    }
                }
            }
            
            .user-info {
                display: flex;
                align-items: center;
                margin-bottom: 20rpx;
                
                .avatar {
                    width: 60rpx;
                    height: 60rpx;
                    border-radius: 30rpx;
                    margin-right: 20rpx;
                }
                
                .nickname {
                    font-size: 28rpx;
                    color: #333;
                    margin-right: 20rpx;
                }
                
                .phone {
                    font-size: 28rpx;
                    color: #666;
                }
            }
            
            .order-info {
                background: #f9f9f9;
                border-radius: 8rpx;
                padding: 20rpx;
                
                .info-item {
                    display: flex;
                    justify-content: space-between;
                    margin-bottom: 10rpx;
                    
                    &:last-child {
                        margin-bottom: 0;
                    }
                    
                    .label {
                        font-size: 26rpx;
                        color: #666;
                    }
                    
                    .value {
                        font-size: 26rpx;
                        color: #333;
                        
                        &.price {
                            color: #f44336;
                            font-weight: bold;
                        }
                    }
                }
            }
            
            .actions {
                margin-top: 20rpx;
                
                .action-btn {
                    width: 100%;
                    height: 80rpx;
                    line-height: 80rpx;
                    border-radius: 40rpx;
                    font-size: 28rpx;
                    
                    &.warn {
                        background: #fff3f3;
                        color: #f44336;
                    }
                }
            }
        }
    }
}
</style> 